
import notification from 'utils/notification';
import util from 'utils/util';
//引入接口
import sysMenuApi from "api/sysMenuApi";
const { queryDataList, sysMenuAdd, sysMenuEdit, sysMenuDel, querySysMenuById, queryTreeList } = sysMenuApi;

export default {
    namespace: 'sysMenuModel',
    state: {
        addShowVisible: false,
        editShowVisible: false,
        detailShowVisible: false,
        tabledata: {
            datalist: [],
            totalSize: 0
        },
        queryParams: {},
        detailData: {},
        editData: {},
        pageSize: 10,
        page: 1,
        menuTreeData: [],
        add_parent_id: ""
    },
    effects: {
        /**
          * 初始化页面
          */
        *initPageData({ payload, callback }, { select, call, put }) {
            //写入数据
            yield put({
                type: 'updateState',
                payload: {
                    pageSize: 10, page: 1, queryParams: {}, tabledata: {
                        datalist: [],
                        totalSize: 0
                    },
                    addShowVisible: false,
                    editShowVisible: false,
                    detailShowVisible: false
                },
            });
            //获取数据
            yield put({
                type: 'querylist',
                payload: {}
            });
            //菜单树形结构
            yield put({
                type: 'queryTreeList',
                payload: {}
            });
        },
        /**
          * 刷新页面
          */
        *refreshPageData({ payload, callback }, { select, call, put }) {
            yield put({
                type: 'updateState',
                payload: {
                    addShowVisible: false,
                    editShowVisible: false,
                    detailShowVisible: false
                },
            });
            //获取数据
            yield put({
                type: 'querylist',
                payload: { refresh: true }
            });
        },
        /**
          * 查询列表
          */
        *querylist({ payload, callback }, { select, call, put }) {
            //获取搜索条件
            const { queryParams } = yield select(_ => _.sysMenuModel);
            let rs = yield call(queryDataList, { queryParams, refresh: payload.refresh || false });
            if (util.verifyErrCode(rs.code, "", rs.msg)) {
                // let datalist = genTreeList(rs.data.tabledata.datalist, "");
                let datalist = toTreeList(rs.data.tabledata.datalist, "menu_id", "parent_id", [["title", "menu_name"], ["value", "menu_id"], ["key", "menu_id"]]);
                //写入数据
                yield put({
                    type: 'updateState',
                    payload: { "tabledata": { datalist } },
                });
            }
        },

        *pageOrPageSizeChange({ payload }, { call, put }) {
            //更新页面大小，当前页数据
            yield put({
                type: 'updateState',
                payload: { pageSize: payload.pageSize, page: payload.page }
            });
            //重新获取列表数据
            yield put({
                type: 'refreshPageData',
                payload: {}
            });
        },

        *querySubmit({ payload }, { call, put }) {
            //设置搜索内容，page设置为1
            yield put({
                type: 'updateState',
                payload: { queryParams: payload.queryParams, page: 1 }
            });
            //重新获取列表数据
            yield put({
                type: 'querylist',
                payload: {}
            });
        },
        *addShow({ payload, callback }, { call, put }) {
            yield put({
                type: 'updateState',
                payload: { addShowVisible: true, add_parent_id: payload.add_parent_id }
            });
        },
        *editShow({ payload, callback }, { call, put }) {
            let rs = yield call(querySysMenuById, payload);
            if (util.verifyErrCode(rs.code, "", rs.msg)) {
                yield put({
                    type: 'updateState',
                    payload: { editShowVisible: true, editData: rs.data }
                });
            }
        },
        *detailShow({ payload, callback }, { call, put }) {
            let rs = yield call(querySysMenuById, payload);
            if (util.verifyErrCode(rs.code, "", rs.msg)) {
                yield put({
                    type: 'updateState',
                    payload: { detailShowVisible: true, detailData: rs.data }
                });
            }
        },
        *addRowData({ payload, callback }, { call, put }) {
            //构建数据提交到服务器
            let rs = yield call(sysMenuAdd, payload.subData);
            if (util.verifyErrCode(rs.code, "保存成功", rs.msg)) {
                //刷新原页面
                yield put({
                    type: 'refreshPageData',
                    payload: {}
                });
                //回调清空表单
                callback({ code: rs.code });
            }
        },
        *editRowData({ payload, callback }, { call, put }) {
            //构建数据提交到服务器
            let rs = yield call(sysMenuEdit, payload);
            if (util.verifyErrCode(rs.code, "编辑并保存成功", rs.msg)) {
                //刷新原页面
                yield put({
                    type: 'refreshPageData',
                    payload: {}
                });
                //回调清空表单
                callback({ code: rs.code });
            }
        },
        *delRowData({ payload, callback }, { call, put }) {
            let rs = yield call(sysMenuDel, payload);
            if (util.verifyErrCode(rs.code, "删除成功", rs.msg)) {
                //刷新原页面
                yield put({
                    type: 'refreshPageData',
                    payload: {}
                });
            }
        },
        *queryTreeList({ payload, callback }, { call, put }) {
            let rs = yield call(queryTreeList, payload);
            if (util.verifyErrCode(rs.code, "", rs.msg)) {
                // let menuTreeData = genTreeList(rs.data.menuTreeData, "");
                let menuTreeData = toTreeList(rs.data.menuTreeData, "menu_id", "parent_id", [["title", "menu_name"], ["value", "menu_id"], ["key", "menu_id"]]);
                
                yield put({
                    type: 'updateState',
                    payload: { menuTreeData }
                });
            }
        },
    },

    reducers: {
        updateState(state, { payload }) {
            return {
                ...state,
                ...payload,
            }
        },
    }
}

/**
 * 构建节点树
 * @param {*} list 
 * @param {*} parent_id 
 */
function genTreeList(list, parent_id) {
    let retList = [];
    for (var i = 0; i < list.length; i++) {
        let treeItem = list[i];
        treeItem.title = treeItem.menu_name;
        treeItem.value = treeItem.menu_id;
        treeItem.key = treeItem.menu_id;
        // console.log(`${parent_id} == ${treeItem.menu_id}`, parent_id == treeItem.menu_id);
        if (parent_id == treeItem.parent_id) {
            let childList = genTreeList(list, treeItem.menu_id);
            if (childList.length > 0) {
                treeItem.children = childList;
            }
            retList.push(treeItem);
        }
    }
    return retList;
}

function toTreeList(data, primary_key, parent_key, mapkey) {
    let result = [];

    //检验数据是否符合规范
    if (!Array.isArray(data) || (!primary_key) || (!parent_key)) {
        return result
    }
    //键值映射关系
    if (!Array.isArray(mapkey)) {
        mapkey = [];
    }

    data.forEach(item => {
        delete item.children;
    });
    let map = {};
    data.forEach(item => {
        map[item[primary_key]] = item;
    });
    data.forEach(item => {
        let parent = map[item[parent_key]];
        //关系映射
        for (var i = 0; i < mapkey.length; i++) {
            let mapItem = mapkey[i];
            //锁定映射关系是否合法
            if (Array.isArray(mapItem)) {
                if (mapItem.length == 2) {
                    item[mapItem[0]] = item[mapItem[1]];
                }
            }
        }
        if (parent) {
            (parent.children || (parent.children = [])).push(item);
        } else {
            result.push(item);
        }
    });
    return result;
}